package cn.bud.msgbus.server.web.ctrl;

import cn.hutool.core.collection.CollectionUtil;
import com.zl9c.general.bus.bean.MsgBody;
import com.zl9c.general.bus.busdao.BusDao;
import com.zl9c.general.bus.config.BusConfig;
import com.zl9c.general.bus.server.MsgBusDataPusher;
import com.zl9c.general.bus.server.MsgBusServer;
import com.zl9c.general.bus.server.subscribe.HttpSubscriber;
import com.zl9c.general.bus.web.dtq.SubscribeHttpDTQ;
import com.zl9c.general.swagger2.common.QueryResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * MsgBusCtrl
 *
 * @author hxj
 * @version 1.0
 * @description
 * @date 2024-07-15 13:22
 */
@Api(tags = "消息总线")
@RestController
@RequestMapping("/api/v1/general/bus/")
public class MsgBusCtrl {

    @Resource
    BusConfig busConfig;
    @Resource
    private BusDao busDao;

    @Resource
    private MsgBusDataPusher msgBusDataPusher;

    @ApiOperation(value = "http订阅")
    @PostMapping("subscribe/http")
    public QueryResult<Boolean> subscribeHttp(@RequestBody SubscribeHttpDTQ dtq) {
        MsgBusServer busServer = busConfig.busServer();
        if (busServer == null) {
            return new QueryResult<>(false);
        }

        HttpSubscriber httpSubscriber = new HttpSubscriber();
        httpSubscriber.setUrl(dtq.getCallbackUrl());
        for (String topic : dtq.getTopics()) {
            httpSubscriber.addTopic(topic, dtq.getStartTime(), dtq.getEndTime());
        }
        busDao.editSubscriber(httpSubscriber);

        if (CollectionUtil.isNotEmpty(dtq.getTopics())) {
            SubscribeHttpDTQ.validUrl(dtq.getCallbackUrl());
            busServer.addSubscriber(httpSubscriber);
        }else {
            busServer.delSubscriber(dtq.getCallbackUrl());
        }
        return new QueryResult<>(true);
    }

    @ApiOperation(value = "http推送消息")
    @PostMapping("msg/push")
    public QueryResult<Boolean> pushMsg(@RequestBody MsgBody msgBody) {
        msgBusDataPusher.pushMsg(msgBody);
        return new QueryResult<>(true);
    }
}
